<?php 

class paomeShareController extends base
{
    
    public function __construct()
    {
        parent::__construct('show');
        $this->in_user();
    }

    
    /**
    * 分享页跳转链接
    */
    public function doshareLink()
    {
        $uid = common::request('target_uid');
        //判断用户是否在app中
        if(common::isInAppWebview()){
            $shareUrl = "http://".$this->config['host']."/paome_webIndex/sharePao?target_uid=".$uid;
            common::go($shareUrl);
        }else{
            $wxUrl = $this->load('paome/share')->pubOpenIdUrl($uid);
            common::go($wxUrl);
        }
    }

    /**
    * 微信回调
    */
    public function dowxCallback()
    {
        $uid = common::request('target_uid');
        /*if(!$this->load('user')->getWxPubOpenId())
        {*/
            $this->loadLib('wx');
            $code = $_GET['code'];
            $state = $_GET['state'];
            $wx = new wx();
            $tokenInfo = $wx->getToken($code, $state);
            $token = $tokenInfo['access_token'];
            $openid = $tokenInfo['openid'];
            $userInfo = $wx->getUserInfo($token, $openid);
            $nickname = 'wx'.time();
            $header = 'http://irun.hupu.com/static/images/4.jpg';
            if(!empty($userInfo)){
                isset($userInfo['nickname']) && $nickname = $userInfo['nickname'];
                isset($userInfo['headimgurl']) && $header = $userInfo['headimgurl'];
            }
            $playInfo = array(
                'openid' => $openid,
                'nickname' => $nickname,
                'header' => $header
            );
            $playInfo = json_encode($playInfo);
            setcookie('wxpo', $playInfo, time() + 86400, '/', '.hupu.com', FALSE, TRUE);
            setcookie('wxpo', $playInfo, time() + 86400, '/', '.ijoggers.com', FALSE, TRUE);
        //}

        //$this->_getUrl();
        /*$url = $this->load("connect")->_getUrl();
        common::go($url);*/
        //common::go("http://".$this->config['host'].'/paome_webIndex/sharePao?target_uid='.$uid);
        common::go("http://irun.hupu.com/paome_webIndex/sharePao?target_uid=".$uid);
    }

    /**
    * 分享模块--奖品信息
    */
    public function dosharePrizeInfo()
    {
        /*$uid = $this->uid; 
        if(empty($uid))
        {
          $_ENV['error']->getErrors(201);
          exit;
        }*/
        
        $p = common::request('p', 'R', 1);   //页码
        $contestId = common::request('contestId', 'R');   //赛季id
        
        $countSql = "select count(1) from r_pm_share_prize where is_show = 0";
        !empty($contestId) && $countSql .= " and contest_id = {$contestId}";
        $num = $this->db->getOne($countSql);

        $search = compact('contestId');
        //分页
        $offset = 20;
        $parameter = "&contestId=".$contestId;
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset, $parameter);
        $pageStr = $page->show();
        $start = ($p - 1) * $offset;

        $sql = "select * from r_pm_share_prize where is_show = 0";
        !empty($contestId) && $sql .= " and contest_id = {$contestId}";
        $sql .= " order by contest_id desc limit $start,$offset";

        $list = $this->db->getAll($sql);
        
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('search', $search);  //搜索条件
        $this->view->assign('list', $list);  
        $this->view->display('paome/sharePrizeInfo');
    }

    /**
    * 分享模块--后台配置奖品
    */
    public function dosharePrizeUpdate()
    {
        $pid = intval(common::request('pid', 'R'));

        //根据id获取奖品信息
        $prizeInfo = array();
        $isNew = false;
        if($pid){    //update
            $isNew = true;
            $prizeInfo = $this->db->getRowTable('r_pm_share_prize', array(), "pid = {$pid}");
        }

        if(common::method() == 'POST')
        {   
            //活动结束后不可以点赞抽奖
            $season = $this->load('paome/paomeHall')->getCurrentSeason();
            if(empty($season) || time() > $season['end_time']){
                exit("这个时间段暂无赛季信息！");
            }
            $name = common::request('name', 'P');
            $count = common::request('count', 'P');
            $odds = common::request('odds', 'P');
            $day_number = common::request('day_number', 'P');
            $isInfinite = common::request('isInfinite', 'P');
            $is_show = common::request('is_show', 'P');
            $contest_id = $season['id'];

            $params = compact('name','count','odds','day_number','isInfinite','contest_id', 'is_show');

            if($pid){   //update
                $params['pid'] = $pid;
                $this->db->updateRowTable('r_pm_share_prize', $params);
            }else{
                $params['remain_count'] = $count;
                $this->db->insertRowTable('r_pm_share_prize', $params);
            }
            common::go("http://".$this->config['host'].'/paome_share/sharePrizeInfo');
        }else{
            !$prizeInfo && $prizeInfo = array('pid' => '', 'name' => '', 'count' => '', 'odds' => '', 'day_number' => '', 'isInfinite' => 0, 'is_show' => 0);

            $this->view->assign('isNew', $isNew);
            $this->view->assign('prizeInfo', $prizeInfo);
            $this->view->display('paome/sharePrizeUpdate');
        }
    }

    /**
    * 分享模块--用户中奖信息
    */
    public function doshareUserWin()
    {
        /*$uid = $this->uid; 
        if(empty($uid))
        {
          $_ENV['error']->getErrors(201);
          exit;
        }*/
        
        $p = common::request('p', 'R', 1);   //页码
        $contestId = common::request('contestId', 'R');   //赛季id
        
        $countSql = "select count(1) from r_pm_share_winning where 1=1 ";
        !empty($contestId) && $countSql .= " and contest_id = {$contestId}";
        $num = $this->db->getOne($countSql);

        $search = compact('contestId');
        //分页
        $offset = 20;
        $parameter = "&contestId=".$contestId;
        require FILE . 'lib/page.class.php';
        $page = new Page($num, $offset, $parameter);
        $pageStr = $page->show();
        $start = ($p - 1) * $offset;

        $sql = "select w.*,p.name from r_pm_share_winning w LEFT JOIN r_pm_share_prize p ON p.pid = w.prize where 1=1 ";
        !empty($contestId) && $sql .= " and contest_id = {$contestId}";
        $sql .= " order by contest_id,add_time desc limit $start,$offset";

        $list = $this->db->getAll($sql);
        if($list){
            foreach ($list as &$v) {
                $v['pCity'] = $v['provice'] .'-'. $v['city'];
                $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            }
        }

        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('search', $search);  //搜索条件
        $this->view->assign('list', $list);  
        $this->view->display('paome/shareUserWin');
    }

    /**
    * 分享页--主页
    */
    public function doshareHome()
    {
        $this->printResult = TRUE;
        $uid = common::request('target_uid','R');    //分享者id
        //$openId = $_COOKIE['wxpo'];
        $playInfo = isset($_COOKIE['wxpo']) ? $_COOKIE['wxpo'] : '';
        !empty($playInfo) && $playInfo = json_decode($playInfo, true);
        $openId = $playInfo ? $playInfo['openid'] : 333;
        if(empty($uid))
        {
          $_ENV['error']->getErrors(101);
          exit;
        }

        //获取用户人气数据
        $userInfo = $this->load('paome/center')->getUserPopularity($uid);
        //获取用户当天点赞剩余次数
        $lightTimes = $this->load('paome/center')->getLightTimes($openId);
        $lightTimes = $lightTimes ? $lightTimes : 0;
        $remainTimes = 3 - $lightTimes;  //剩余抽奖次数
        //人气榜(前十名)
        $sentimentList = $this->load("paome/paomeHall")->getHallOfFameList('support_num');
        $rankList = array();
        if($sentimentList){
            foreach ($sentimentList as $key => $val) {
               $rankList[$key]['nickname'] = $val['nickname'];
               $rankList[$key]['header'] = $val['header'];
               $rankList[$key]['support_num'] = $val['support_num'];
            }
        }

        $this->result['result']['remainTimes'] = $remainTimes;
        $this->result['result']['rankList'] = $rankList;
        $this->result['result']['userInfo'] = $userInfo;
        /*$this->view->assign('remainTimes', $remainTimes);
        $this->view->assign('sentimentList', $sentimentList);
        $this->view->assign('userInfo', $userInfo);  
        $this->view->display('paome/run/share');*/
    }

    /**
    * 分享页--点赞抽奖
    */
    public function doshareDraw()
    {
        $this->printResult = TRUE;
        $target_uid = common::request('target_uid','R');
        //$openId = $playInfo ? $playInfo['openid'] : 333;
        $date = date('Ymd');
        //判断用户是否在app中
        if(common::isInAppWebview()){
            $selfUid = $this->uid;
            if(empty($selfUid) || empty($target_uid)){
                $_ENV['error']->getErrors(201);
                exit; 
            }
            if($selfUid == $target_uid){
                $_ENV['error']->getErrors(6030);
                exit;
            }
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $selfUid, 'nickname') ? $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $selfUid, 'nickname') : "app".time();
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $selfUid, 'header') ? $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $selfUid, 'header') : "http://joggers-test.qiniudn.com/tba79f85a7bea2b8a4b84bb9afdcfa2dd1.jpg";

            //查看该用户当天剩余可抽奖次数
            $lightTimes = $this->redis->get(REDIS_PREFIX . "uid_" . $selfUid . "_target_uid_" . $target_uid . "_date_" . $date);
            $lightTimes = $lightTimes ? $lightTimes : 0;
            if($lightTimes == 3){
                $_ENV['error']->getErrors(7001);
                exit;
            } 
            $lightTimes = $lightTimes + 1;
            $this->redis->set(REDIS_PREFIX . "uid_" . $selfUid . "_target_uid_" . $target_uid . "_date_" . $date, $lightTimes);
            $this->redis->expire(REDIS_PREFIX . "uid_" . $selfUid . "_target_uid_" . $target_uid . "_date_" . $date, 86400);
        }else{
            $playInfo = isset($_COOKIE['wxpo']) ? $_COOKIE['wxpo'] : '';
            !empty($playInfo) && $playInfo = json_decode($playInfo, true);
            $openId = 0;
            $header = '';
            $nickname = '';
            if(!empty($playInfo)){
                $openId = $playInfo['openid'];
                $header = $playInfo['header'] ? $playInfo['header'] : 'http://irun.hupu.com/static/images/4.jpg';
                $nickname = $playInfo['nickname'] ? $playInfo['nickname'] : 'wx'.time();
            }

            if(!$openId || !$target_uid){
                $_ENV['error']->getErrors(101);
                exit;
            }

            //查看该用户当天剩余可抽奖次数
            $lightTimes = $this->redis->get(REDIS_PREFIX . "openId_" . $openId . "_target_uid_" . $target_uid . "_date_" . $date);
            $lightTimes = $lightTimes ? $lightTimes : 0;
            if($lightTimes == 3){
                $_ENV['error']->getErrors(7001);
                exit;
            } 
            $lightTimes = $lightTimes + 1;
            $this->redis->set(REDIS_PREFIX . "openId_" . $openId . "_target_uid_" . $target_uid . "_date_" . $date, $lightTimes);
            $this->redis->expire(REDIS_PREFIX . "openId_" . $openId . "_target_uid_" . $target_uid . "_date_" . $date, 86400);
        }
        
        $userClub = $this->load('paome/paomeClub')->getUserCurrentClubInfo($target_uid);
        if(empty($userClub)){
            $_ENV['error']->getErrors(6027);
            exit;
        }

        //活动结束后不可以点赞抽奖
        $season = $this->load('paome/paomeHall')->getCurrentSeason();
        if(empty($season) || time() > $season['end_time']){
            $_ENV['error']->getErrors(2010);
            exit;
        }
        //获取当前所处轮次
        $round = $this->load('paome/paomeHall')->getCurrentRound();
        $round = $round ? $round : 0;   //招募期

        //读取该赛季内的奖品信息
        $prizeList = $this->db->getAll("select * from r_pm_share_prize where is_show = 0 and contest_id = {$season['id']}");
        $drawInfo = array();
        $date = date('Ymd');
        if($prizeList){
            foreach ($prizeList as &$v) {
                $drawInfo[$v['pid']] = $v['name'];
                if($v['isInfinite'] == 0){  //考虑奖品个数
                    if($v['remain_count'] == 0){   //剩余数量为0，概率置0
                        $v['odds'] = 0;
                    }
                }
                if(!empty($v['day_number'])){  //每天个数限制
                    $restrict = $this->redis->hget(REDIS_PREFIX . "sharePrize_" . $v['pid'], $date);
                    $restrict = $restrict ? $restrict : 0;
                    if($restrict >= $v['day_number']){
                        $v['odds'] = 0;
                    }
                }

                for($i=0; $i<$v['odds']; $i++){
                    $result[] = $v['pid'];
                }
            }

            shuffle($result);
            $prizeId = $result[array_rand($result)]; //所获奖品
            $num = $this->redis->hget(REDIS_PREFIX . "sharePrize_" . $prizeId, $date);
            $num = $num ? $num : 0;
            $num += 1;
            $this->redis->hset(REDIS_PREFIX . "sharePrize_" . $prizeId, $date, $num);
            $this->redis->expire(REDIS_PREFIX . "sharePrize_" . $prizeId, 86400);
            //暂存用户中奖信息
            if(common::isInAppWebview()){
                $this->redis->set(REDIS_PREFIX . "shareuid_" . $selfUid, $prizeId);
            }else{
                $this->redis->set(REDIS_PREFIX . "shareOpenId_" . $openId, $prizeId);
            }

            //更新奖品库存
            $this->db->update("update r_pm_share_prize set remain_count = remain_count - 1 where isInfinite = 0 and is_show = 0 and pid = {$prizeId}");

            $light = 10;  //mt_rand(1, 30);  //点赞数
            //组装中奖信息
            $winningInfo = array(
                'id' => $prizeId,
                'name' => $drawInfo[$prizeId],
                'remainTimes' => 3 - $lightTimes,
                'light' => $light,
                'userName' => $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $target_uid, 'nickname')
            );
            //查询当天是否有对该用户点赞信息
            if(common::isInAppWebview()){
                $sql = "select * from r_pm_supporters where uid = {$selfUid} and target_uid = {$target_uid} and date = {$date}";
                $isLight = $this->db->getAll($sql);
                if(!empty($isLight)){  //存在，更新
                    $this->db->update("update r_pm_supporters set light_times = light_times + 1, light = light + {$light} where uid = {$selfUid} and target_uid = {$target_uid} and date = \"{$date}\"");
                }else{    //不存在，新增
                    $param = array(
                        'contest_id' => $season['id'], 
                        'target_uid' => $target_uid, 
                        'round' => $round, 
                        'type' => 2, 
                        'light' => $light,
                        'date' => $date,
                        'is_share' => 1, 
                        'uid' => $selfUid, 
                        'user_name' => $nickname, 
                        'user_header' => $header,
                        'light_times' => 1 
                    );
                    //跑么杯人气表更新
                    $isInsert = $this->db->insertRowTable('r_pm_supporters', $param);
                }
            }else{
                $sql = "select * from r_pm_supporters where open_id = \"{$openId}\" and target_uid = {$target_uid} and date = {$date}";
                $isLight = $this->db->getAll($sql);
                if(!empty($isLight)){  //存在，更新
                    $this->db->update("update r_pm_supporters set light_times = light_times + 1, light = light + {$light} where open_id = \"{$openId}\" and target_uid = {$target_uid} and date = \"{$date}\"");
                }else{    //不存在，新增
                    $param = array(
                        'contest_id' => $season['id'], 
                        'target_uid' => $target_uid, 
                        'round' => $round, 
                        'type' => 2, 
                        'light' => $light,
                        'date' => $date,
                        'is_share' => 1, 
                        'open_id' => $openId, 
                        'user_name' => $nickname, 
                        'user_header' => $header,
                        'light_times' => 1 
                    );
                    //跑么杯人气表更新
                    $isInsert = $this->db->insertRowTable('r_pm_supporters', $param);
                }
            }
            
            $this->load('paome/cup')->addSupportNum($target_uid, $light, 2);

            $this->result['result']['winningInfo'] = $winningInfo;
        }else{
            $_ENV['error']->getErrors(7002);
            exit;
        }
    }

    /**
    * 分享页--填写领奖信息
    */
    public function doshareWinning(){
        $this->printResult = TRUE;
        $realname = common::request('realname', 'R','');
        $phone = common::request('phone', 'R','');
        $provice = common::request('provice', 'R','');
        $city = common::request('city', 'R','');
        $address = common::request('address', 'R','');
        $prize = common::request('prize', 'R','');

        //判断用户是否在app中
        if(common::isInAppWebview()){
            $selfUid = $this->uid;
            if(empty($selfUid) || !$prize){
                $_ENV['error']->getErrors(201);
                exit; 
            }
            //判断用户是否有该中奖信息
            $pId = $this->redis->get(REDIS_PREFIX . "shareuid_" . $selfUid);
            if($prize != $pId){
                $_ENV['error']->getErrors(7003);
                exit;
            }
            $this->redis->del(REDIS_PREFIX . "shareuid_" . $selfUid);
        }else{
            $playInfo = isset($_COOKIE['wxpo']) ? $_COOKIE['wxpo'] : '';
            !empty($playInfo) && $playInfo = json_decode($playInfo, true);
            $open_id = $playInfo ? $playInfo['openid'] : 0;
            if(!$open_id || !$prize){
                $_ENV['error']->getErrors(101);
                exit;
            }
            //判断用户是否有该中奖信息
            $pId = $this->redis->get(REDIS_PREFIX . "shareOpenId_" . $open_id);
            if($prize != $pId){
                $_ENV['error']->getErrors(7003);
                exit;
            }
            $this->redis->del(REDIS_PREFIX . "shareOpenId_" . $open_id);
        }
        //活动结束后不可以领奖
        $season = $this->load('paome/paomeHall')->getCurrentSeason();
        if(empty($season) || time() > $season['end_time']){
            $_ENV['error']->getErrors(2010);
            exit;
        }
        $contest_id = $season['id'];
        
        if(!common::checkPhone($phone)){
            $_ENV['error']->getErrors(3008);
            exit;
        }
        
        $add_time = time();
        if(common::isInAppWebview()){
            $uid = $selfUid;
            $params = compact('uid', 'contest_id', 'realname', 'phone', 'provice', 'city', 'address', 'prize', 'add_time');
        }else{
            $params = compact('open_id', 'contest_id', 'realname', 'phone', 'provice', 'city', 'address', 'prize', 'add_time');
        }
        
        $wid = $this->db->insertRowTable('r_pm_share_winning', $params);
        $this->result['result']['wid'] = $wid;
    }
}